<template>
  <a-modal title="新增机构" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="orgAddVisiable">
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='法人行号' v-bind="formItemLayout">
            <a-input v-decorator="['instId']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="创建机构号" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
            style="display: none">
            <a-input v-decorator="['crtOrgId']" />
            <a-input v-decorator="['id']" />
            <a-input v-decorator="['orgStatus']" />
            <a-input v-decorator="['oprId']" />
            <a-input v-decorator="['createTime']" />
            <a-input v-decorator="['lastOprId']" />
            <a-input v-decorator="['lastUpdateTime']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构类型' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" @change="handleOrgTypeChange"
              v-decorator="['orgType', { rules: [{ required: true, message: '请选择机构类型' }] }]">
              <a-select-option key="00">银行机构</a-select-option>
              <a-select-option key="01">代理机构虚拟机构</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构级别' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%"
              v-decorator="['orgLevel', { rules: [{ required: true, message: '请选择机构级别' }] }]">
              <a-select-option key="00">总行</a-select-option>
              <a-select-option key="01">分行</a-select-option>
              <a-select-option key="02">支行</a-select-option>
              <a-select-option key="03">营业部/网点</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构编码' v-bind="formItemLayout" :validateStatus="orgCodeStatus" :help="orgCodehelp">
            <a-input @blur="handleOrgCodeBlur" v-decorator="['orgCode',
            {
              rules: [
                { required: true, message: '机构编码不能为空' },
                { max: 20, message: '长度不能超过20个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构名称' v-bind="formItemLayout">
            <a-input v-decorator="['orgName',
            {
              rules: [
                { required: true, message: '机构名称不能为空' },
                { max: 100, message: '长度不能超过100个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联行号' v-bind="formItemLayout">
            <a-input v-decorator="['bankBranchCode',
            {
              rules: [
                { required: true, message: '联行号不能为空' },
                { max: 14, message: '长度不能超过14个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='内部银行代码' v-bind="formItemLayout">
            <a-input v-decorator="['innerBankCode',
            {
              rules: [
                { required: true, message: '内部银行代码不能为空' },
                { max: 20, message: '长度不能超过20个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构联系人' v-bind="formItemLayout">
            <a-input v-decorator="['contactName',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人地址' v-bind="formItemLayout">
            <a-input v-decorator="['contactAddress',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人传真' v-bind="formItemLayout">
            <a-input v-decorator="['contactFax',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人电话' v-bind="formItemLayout">
            <a-input v-decorator="['contactPhone',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人邮编' v-bind="formItemLayout">
            <a-input v-decorator="['contactZipCode',
            {
              rules: [
                { max: 6, message: '长度不能超过6个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人邮箱' v-bind="formItemLayout">
            <a-input v-decorator="['contactMail',
            {
              rules: [
                { max: 40, message: '长度不能超过40个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 4rem !important">
        <a-col :md="12" :sm="24">
          <a-form-item label='上级机构' style="margin-bottom: 2rem" v-bind="formItemLayout">
            <a-tree v-show="orgParent.id == ''" :key="orgTreeKey" :multiple="false" :checkable="true"
              :checkStrictly="true" @check="handleCheck" @expand="handleExpand" :expandedKeys="expandedKeys"
              :treeData="orgTreeData">
            </a-tree>

            <a-input v-show="orgParent.id != ''" v-decorator="['parentOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-org slot="overlay">
          <a-org-item key="1" @click="expandAll">展开所有</a-org-item>
          <a-org-item key="2" @click="closeAll">合并所有</a-org-item>
        </a-org>
        <a-button>
          树操作
          <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
    <!--    <icons
      @choose="handleIconChoose"
      @close="handleIconCancel"
      :iconChooseVisible="iconChooseVisible">
    </icons>-->
  </a-modal>
</template>
<script>
// import Icons from './Icons'
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'OrgAdd',
  // components: {Icons},
  props: {
    orgAddVisiable: {
      default: false
    },
    orgInstId: '',
    orgParent: {
      id: "",
      orgCode: ""
    }
  },
  data() {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',
      help: '',
      orgTreeKey: +new Date(),
      org: {
        icon: ''
      },
      checkedKeys: [],
      expandedKeys: [],
      orgTreeData: [],
      idToOrgCodeData: [],
      iconChooseVisible: false,
      orgCodeStatus: '',
      orgCodehelp: ''
    }
  },
  computed: {
    show: {
      get: function () {
        return this.orgAddVisiable
      },
      set: function () {
      }
    }
  },
  methods: {
    //验证机构代码是否存在
    handleOrgCodeBlur() {
      let orgCode=this.form.getFieldValue('orgCode');
      this.orgCodeStatus = 'validating'
      this.orgCodehelp=''
      for (let i in this.idToOrgCodeData) {   
            if (orgCode === this.idToOrgCodeData[i]) {
              this.orgCodeStatus='error'
              this.orgCodehelp='抱歉，该机构编码已存在'
              //  this.$message.error('抱歉，该机构编码已存在,请重新输入') 
           }        
      }
    },
    reset() {
      this.loading = false
      this.orgTreeKey = +new Date()
      this.expandedKeys = this.checkedKeys = []
      this.org = {}
      this.form.resetFields()
    },
    async handleOrgTypeChange(value) {
      try {
        const r = await this.$get('admin/upmporg', {
          instId: this.orgInstId,
          orgType: value,
          orgStatus: '01'
        });
        this.orgTreeData = r.data.rows.children
        this.allTreeKeys = r.data.ids
        this.idToOrgCodeData = r.data.idToCode


        this.orgTreeKey = +new Date()
      } catch (e) {
        console.error(e);
      }
    },
    onClose() {
      this.reset()
      this.$emit('close')
      this.orgCodeStatus = 'validating'
      this.orgCodehelp=''
    },
    handleCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    chooseIcons() {
      this.iconChooseVisible = true
    },
    handleIconCancel() {
      this.iconChooseVisible = false
    },
    handleIconChoose(value) {
      this.org.icon = value
      this.iconChooseVisible = false
    },
    deleteIcons() {
      this.org.icon = ''
    },
    handleSubmit() {
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked
      if (checkedArr.length < 1) {
        this.$message.error('必须选择一个上级菜单，请选择')
        return
      }
      if (checkedArr.length > 1) {
        this.$message.error('最多只能选择一个上级菜单，请修改')
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.setOrgFields()
          this.loading = true
          if ("" != this.orgParent.id) {
            this.org.parentId = this.orgParent.id
            this.org.parentOrgCode = this.orgParent.orgCode;

          } else {
            if (checkedArr.length) {
              this.org.parentId = checkedArr[0]
              this.org.parentOrgCode = this.idToOrgCodeData[this.org.parentId];
            } else {
              this.org.parentId = ''
            }
          }
          this.org.instId = this.orgInstId;

          this.$post('admin/upmporg', {
            ...this.org
          }).then(() => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    setOrgFields() {
      let fields = ['id', 'instId', 'orgType', 'orgCode', 'orgName', 'bankBranchCode', 'innerBankCode',
        'contactName', 'orgLevel', 'contactAddress', 'contactFax', 'contactMail', 'contactPhone'
        , 'contactZipCode', 'orgStatus', 'crtOrgId', 'oprId', 'createTime', 'lastOprId', 'lastUpdateTime']

      let values = this.form.getFieldsValue(fields)
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => {
          this.org[_key] = values[_key]
        })
      }
    }
  },
  watch: {
    orgAddVisiable() {
      if (this.orgAddVisiable) {
        this.$get('admin/upmporg', {
          instId: this.orgInstId
        }).then((r) => {
          this.orgTreeData = r.data.rows.children
          this.allTreeKeys = r.data.ids
          this.idToOrgCodeData = r.data.idToCode
          this.orgTreeKey = +new Date()
        })

        this.form.getFieldDecorator("instId");
        this.form.setFieldsValue({ "instId": this.orgInstId })
        if ("" != this.orgParent.id) {//显示上级机构号
          this.form.getFieldDecorator("parentOrgCode");
          this.form.setFieldsValue({ "parentOrgCode": this.orgParent.orgCode })
        }
      }
    }
  }
}
</script>
